<template>
  <div class="ai-chat-page">
    <div class="ios-container">
      <div class="ios-navbar">
        <IOSBackButton @click="router.back()" />
        <h1 class="navbar-title">AI聊天</h1>
        <button class="clear-btn" @click="clearMessages" :disabled="isLoading">
          <svg
            width="20"
            height="20"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
          >
            <polyline points="3,6 5,6 21,6"></polyline>
            <path
              d="m19,6v14a2,2 0 0,1 -2,2H7a2,2 0 0,1 -2,-2V6m3,0V4a2,2 0 0,1 2,-2h4a2,2 0 0,1 2,2v2"
            ></path>
            <line x1="10" y1="11" x2="10" y2="17"></line>
            <line x1="14" y1="11" x2="14" y2="17"></line>
          </svg>
        </button>
      </div>

      <!-- 聊天消息区域 -->
      <ChatMessageList
        v-show="!isInitialLoading"
        ref="chatMessageListRef"
        :messages="messages"
        :is-loading="isLoading"
      />

      <!-- 初始加载动画 -->
      <div v-if="isInitialLoading" class="initial-loading-container">
        <div class="robot-loading">
          <div class="robot-head">
            <div class="robot-eyes">
              <div class="robot-eye left"></div>
              <div class="robot-eye right"></div>
            </div>
            <div class="robot-mouth"></div>
          </div>
          <div class="robot-body">
            <div class="robot-arm left"></div>
            <div class="robot-arm right"></div>
          </div>
          <div class="loading-dots">
            <div class="dot"></div>
            <div class="dot"></div>
            <div class="dot"></div>
          </div>
        </div>
        <div class="loading-text">正在加载聊天记录...</div>
      </div>

      <!-- 输入区域 -->
      <ChatInput :is-loading="isLoading" @send-message="sendMessage" />
    </div>
  </div>
</template>

<script setup>
import IOSBackButton from "~/components/IOSBackButton.vue";
import ChatMessageList from "~/components/ai-chat/ChatMessageList.vue";
import ChatInput from "~/components/ai-chat/ChatInput.vue";

const router = useRouter();
const chatMessageListRef = ref(null);

// 响应式数据
const messages = ref([]);
const isLoading = ref(false);
const isInitialLoading = ref(true);

// 页面加载时获取历史消息
onMounted(async () => {
  await loadChatHistory();
});

const curText = ref("");
const textIndex = ref(0);

const closeInSeconds = (seconds = 2) => {
  return new Promise((resolve) => {
    setTimeout(resolve, seconds * 1000);
  });
};

const checkContinue = () => {
  return textIndex.value < curText.value.length;
}

const createTextAnimation = async (index) => {
  // await nextTick();
  await new Promise((r) => requestAnimationFrame(r));
  if (checkContinue()) messages.value[index].content += curText.value[textIndex.value++];
  if (checkContinue()) messages.value[index].content += curText.value[textIndex.value++];

  if (checkContinue()) return createTextAnimation(index);
  
  await closeInSeconds(4);
  if (checkContinue()) return createTextAnimation(index);
  else {
    curText.value = '';
    textIndex.value = 0;
    saveChatHistory();
  }
};

// 发送消息
const sendMessage = async (question) => {
  if (!question || isLoading.value) return;

  const userMessage = {
    type: "user",
    content: question,
    timestamp: new Date(),
  };

  messages.value.push(userMessage);

  // 滚动到底部
  await nextTick();
  chatMessageListRef.value?.scrollToBottom();

  // 创建AI消息占位符
  const aiMessageIndex = messages.value.length;
  messages.value.push({
    type: "ai",
    content: "",
    timestamp: new Date(),
    isStreaming: true,
  });

  isLoading.value = true;

  try {
    // 使用EventSource进行流式请求
    const eventSource = new EventSource(
      `/api-next/ask?question=${encodeURIComponent(question)}`
    );

    eventSource.onmessage = function (event) {
      try {
        console.log("event success: ", event);
        const data = JSON.parse(event.data);

        // 更新AI消息内容
        if (data.content || data.delta || data.text) {
          const content = data.content || data.delta || data.text;
          // messages.value[aiMessageIndex].content += content
          curText.value += content
            .replace(/<think>/g, "```text\n")
            .replace(/<\/think>/g, "\n```");

          // 滚动到底部
          nextTick().then(() => {
            chatMessageListRef.value?.scrollToBottom();
          });
        }

        // 如果收到结束标志
        if (data.done || data.finished || event.data === "[DONE]") {
          eventSource.close();
          messages.value[aiMessageIndex].isStreaming = false;
          isLoading.value = false;

          // 保存聊天记录
          saveChatHistory();
        }
      } catch (parseError) {
        console.debug("Parse error, treating as plain text:", parseError);
        // 如果不是JSON格式，直接添加到内容中
        if (event.data && event.data !== "[DONE]") {
          // messages.value[aiMessageIndex].content += event.data;
          curText.value += event.data;
          nextTick().then(() => {
            chatMessageListRef.value?.scrollToBottom();
          });
        }
      }
    };

    eventSource.onerror = function (error) {
      console.log("EventSource Error:", JSON.stringify(error));
      eventSource.close();

      if (messages.value[aiMessageIndex].content === "") {
        messages.value[aiMessageIndex].content =
          "抱歉，服务暂时不可用，请稍后再试。";
      }

      messages.value[aiMessageIndex].isStreaming = false;
      isLoading.value = false;

      nextTick().then(() => {
        chatMessageListRef.value?.scrollToBottom();
        saveChatHistory();
      });
    };

    eventSource.onopen = function () {
      console.log("EventSource connection opened");
      createTextAnimation(aiMessageIndex);
    };

    // 设置超时处理
    setTimeout(() => {
      if (isLoading.value) {
        eventSource.close();
        if (messages.value[aiMessageIndex].content === "") {
          messages.value[aiMessageIndex].content = "请求超时，请稍后再试。";
        }
        messages.value[aiMessageIndex].isStreaming = false;
        isLoading.value = false;
        saveChatHistory();
      }
    }, 30000); // 30秒超时
  } catch (error) {
    console.error("Failed to create EventSource:", error);

    // 如果EventSource创建失败，尝试使用POST请求
    try {
      const response = await fetch("/api-next/ask", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          question: question,
        }),
      });

      if (response.ok) {
        const result = await response.json();
        messages.value[aiMessageIndex].content =
          result.answer ||
          result.data ||
          result.message ||
          "抱歉，我没有理解您的问题。";
      } else {
        messages.value[aiMessageIndex].content =
          "抱歉，服务暂时不可用，请稍后再试。";
      }
    } catch (fetchError) {
      console.error("Fetch fallback error:", fetchError);
      messages.value[aiMessageIndex].content =
        "抱歉，服务暂时不可用，请稍后再试。";
    }

    messages.value[aiMessageIndex].isStreaming = false;
    isLoading.value = false;

    await nextTick();
    chatMessageListRef.value?.scrollToBottom();
    await saveChatHistory();
  }
};

// 保存聊天记录
const saveChatHistory = async () => {
  try {
    await $fetch("/api/chat-history", {
      method: "POST",
      body: {
        action: "save",
        messages: messages.value,
      },
    });
  } catch (error) {
    console.error("Failed to save chat history:", error);
  }
};

// 清理消息
const clearMessages = async () => {
  if (isLoading.value) return;

  if (confirm("确定要清空所有聊天记录吗？此操作不可撤销。")) {
    try {
      // 清空前端消息
      messages.value = [];

      // 清空后端存储
      await $fetch("/api/chat-history", {
        method: "POST",
        body: {
          action: "clear",
        },
      });

      console.log("Chat history cleared successfully");
    } catch (error) {
      console.error("Failed to clear chat history:", error);
      // 如果后端清理失败，重新加载历史记录
      await loadChatHistory();
    }
  }
};

// 加载聊天记录
const loadChatHistory = async () => {
  try {
    const response = await $fetch("/api/chat-history", {
      method: "POST",
      body: {
        action: "load",
      },
    });
    messages.value = response.messages || [];
    await nextTick();
    chatMessageListRef.value?.scrollToBottom();
    setTimeout(() => (isInitialLoading.value = false), 1000)
  } catch (error) {
    console.error("Failed to load chat history:", error);
    setTimeout(() => (isInitialLoading.value = false), 1000)
  }
};


</script>

<style scoped>
.ai-chat-page {
  min-height: 100vh;
  background: #f8f9fa;
  font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Helvetica Neue', sans-serif;
}

.ios-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  box-shadow: 0 0 60px rgba(0, 0, 0, 0.08);
}

.ios-navbar {
  display: flex;
  align-items: center;
  padding: 20px 30px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-title {
  font-size: 20px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
  flex: 1;
  text-align: center;
  letter-spacing: -0.01em;
}

.clear-btn {
  background: none;
  border: none;
  color: #ff3b30;
  padding: 8px;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease;
}

.clear-btn:hover {
  background-color: rgba(255, 59, 48, 0.1);
}

.clear-btn:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.clear-btn:disabled:hover {
  background-color: transparent;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ios-container {
    height: 100vh;
  }

  .ios-navbar {
    padding: 10px 16px;
  }
}

.clear-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border: none;
  background: rgba(0, 0, 0, 0.04);
  border-radius: 10px;
  color: #6e6e73;
  cursor: pointer;
  transition: all 0.2s ease;
}

.clear-btn:hover {
  background: rgba(0, 0, 0, 0.08);
  transform: scale(1.05);
}

.clear-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
  transform: none;
}

.chat-input-container {
  border-top: 1px solid rgba(0, 0, 0, 0.06);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
}

.initial-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  padding: 40px;
  background: #f8f9fa;
}

.robot-loading {
  width: 120px;
  height: 120px;
  position: relative;
  animation: float 3s ease-in-out infinite;
}

.robot-head {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #74b9ff, #0984e3);
  border-radius: 20px;
  position: relative;
  margin: 0 auto;
  box-shadow: 0 10px 30px rgba(0, 123, 255, 0.3);
}

.robot-eyes {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 50px;
  height: 15px;
  display: flex;
  justify-content: space-between;
}

.robot-eye {
  width: 12px;
  height: 12px;
  background: #2d3436;
  border-radius: 50%;
  animation: blink 2s infinite;
}

.robot-eye.right {
  animation-delay: 0.1s;
}

.robot-mouth {
  width: 20px;
  height: 10px;
  background: #2d3436;
  border-radius: 0 0 20px 20px;
  position: absolute;
  bottom: 15px;
  left: 50%;
  transform: translateX(-50%);
  animation: smile 2s ease-in-out infinite;
}

.robot-body {
  width: 60px;
  height: 40px;
  background: linear-gradient(135deg, #00cec9, #00b894);
  border-radius: 15px;
  margin: 10px auto;
  position: relative;
  box-shadow: 0 8px 25px rgba(0, 206, 201, 0.3);
}

.robot-arm {
  width: 8px;
  height: 25px;
  background: linear-gradient(135deg, #fd79a8, #e84393);
  border-radius: 10px;
  position: absolute;
  top: 5px;
  animation: wave 1.5s ease-in-out infinite;
}

.robot-arm.left {
  left: -15px;
  transform-origin: top;
}

.robot-arm.right {
  right: -15px;
  animation-delay: 0.5s;
  transform-origin: top;
}

.loading-dots {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-top: 20px;
}

.loading-dots .dot {
  width: 8px;
  height: 8px;
  background: #74b9ff;
  border-radius: 50%;
  animation: bounce 1.4s ease-in-out infinite both;
}

.loading-dots .dot:nth-child(1) { animation-delay: -0.32s; }
.loading-dots .dot:nth-child(2) { animation-delay: -0.16s; }
.loading-dots .dot:nth-child(3) { animation-delay: 0s; }

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
}

@keyframes blink {
  0%, 90%, 100% {
    transform: scaleY(1);
  }
  95% {
    transform: scaleY(0.1);
  }
}

@keyframes smile {
  0%, 100% {
    transform: translateX(-50%) scaleX(1);
  }
  50% {
    transform: translateX(-50%) scaleX(1.2);
  }
}

@keyframes wave {
  0%, 100% {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(15deg);
  }
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.loading-text {
  margin-top: 60px;
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
  opacity: 0.8;
}
</style>
